﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IniParser;
using IniParser.Model;
using IniParser.Model.Configuration;

namespace ra2map_plus.service
{
    class IniMergeService
    {
        public FileIniDataParser Parser { get; }

        public IniData IniData { get; private set; }

        public string StringData => IniData == null ? null : IniData.ToString();

        public IniMergeService()
        {
            var parser = new FileIniDataParser();

            // 默认的Parser配置
            parser.Parser.Configuration.ThrowExceptionsOnError = false;
            parser.Parser.Configuration.AssigmentSpacer = "";
            parser.Parser.Configuration.SkipInvalidLines = true;
            parser.Parser.Configuration.AllowDuplicateKeys = true;
            parser.Parser.Configuration.OverrideDuplicateKeys = true;
            this.Parser = parser;
        }

        /// <summary>
        /// 修改Parser的配置
        /// </summary>
        /// <param name="action">Action(IniParserConfiguration)</param>
        public void ConfigurationParser(Action<IniParserConfiguration> action)
        {
            action.Invoke(this.Parser.Parser.Configuration);
        }

        public string Merge(string rootIniFilePath, List<string> mergeList)
        {
            if (File.Exists(rootIniFilePath))
            {
                IniData rootIniData = this.Parser.ReadFile(rootIniFilePath);

                for (int i = 0; i < mergeList.Count; i++)
                {
                    var filei = mergeList.ElementAt(i);
                    if (File.Exists(filei))
                    {
                        System.Console.WriteLine($"merging {filei}");
                        var datai = Parser.ReadFile(filei);
                        rootIniData.Merge(datai);
                    }
                    else
                    {
                        System.Console.WriteLine($"{filei} does not exists");
                    }
                }

                this.IniData = rootIniData;
            }
            return this.StringData;
        }

        public void Write(string outputPath)
        {
            System.Console.WriteLine($"writing to {outputPath}");
            Parser.WriteFile(outputPath, this.IniData, Encoding.ASCII);
            System.Console.WriteLine("Success!");
        }
    }
}
